/**
 * 遍历树形形式数据
 * @param data 需要遍历的数据
 * @param callback 回调
 * @param childrenField children 字段名
 */
export function eachTree<T>(
  data?: T[],
  callback?: (item: T, index: number, parent?: T) => void | boolean,
  childrenField = 'children',
  parent?: T,
) {
  if (data) {
    data.forEach((d, i) => {
      if (
        callback
        && callback(d, i, parent) !== false
        && d[childrenField]?.length
      ) {
        eachTree(d[childrenField], callback, childrenField, d)
      }
    })
  }
}

/**
 * 格式化树形数据
 * @param data 需要格式化的数据
 * @param formatter 格式器
 * @param childrenField children 字段名
 * @param resultChildrenField 格式化后的 children 字段名
 */
export function mapTree<T, U>(
  data: T[] | undefined | null,
  formatter: (item: T, index?: number, parent?: U) => U | void | undefined,
  childrenField = 'children',
  resultChildrenField = 'children',
  parent?: U,
): U[] {
  const result: U[] = []
  if (data && data.length) {
    data.forEach((d, i) => {
      const item = formatter(d, i, parent)
      if (item) {
        if (d[childrenField] != null) {
          item[resultChildrenField] = mapTree(
            d[childrenField],
            formatter,
            childrenField,
            resultChildrenField,
            item,
          )
        }
        result.push(item)
      }
    })
  }
  return result
}
